// when animating on canvas, it is best to use requestAnimationFrame instead of setTimeout or setInterval
// not supported in all browsers though and sometimes needs a prefix, so we need a shim
window.requestAnimFrame = ( function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function( callback ) {
            window.setTimeout( callback, 1000 / 60 );
        };
})();

// now we will setup our basic variables for the demo
var cav = document.getElementById( 'cav' );
var ctx = cav.getContext("2d");
    // full screen dimensions
var cw = window.screen.availWidth;
var ch = window.screen.availHeight;
    // firework collection
var fireworks = [];
    // particle collection
var particles = [];
    // 创建hsl的初始颜色值
var hue = 120;
    // when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks
var limiterTotal = 5;
var limiterTick = 0;
    // this will time the auto launches of fireworks, one launch per 80 loop ticks
var timerTotal = 80;
var timerTick = 0;
var mousedown = false;
    // mouse x coordinate,
var mx;
    // mouse y coordinate
var my;

// 设置canvas的宽高
cav.width = cw;
cav.height = ch;

// now we are going to setup our function placeholders for the entire demo

// 获取在min和max之间的随机数
function random( min, max ) {
    return Math.random() * ( max - min ) + min;
}

// 获取两点之间的距离
function calculateDistance( p1x, p1y, p2x, p2y ) {
    var xDistance = p1x - p2x,
        yDistance = p1y - p2y;
    return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
}

// 创建烟花函数
function Firework( sx, sy, tx, ty ) {
    // 实际坐标
    this.x = sx;
    this.y = sy;
    // 开始坐标
    this.sx = sx;
    this.sy = sy;
    // 结束坐标
    this.tx = tx;
    this.ty = ty;
    // 开始跟结束坐标之间的距离
    this.distanceToTarget = calculateDistance( sx, sy, tx, ty );
    this.distanceTraveled = 0;
    // track the past coordinates of each firework to create a trail effect, increase the coordinate count to create more prominent trails
    this.coordinates = [];
    this.coordinateCount = 3;
    // populate initial coordinate collection with the current coordinates
    while( this.coordinateCount-- ) {
        this.coordinates.push( [ this.x, this.y ] );
    }
    this.angle = Math.atan2( ty - sy, tx - sx );
    this.speed = 2;
    this.acceleration = 1.05;   //加速度
    this.brightness = random( 50, 70 );
    // circle target indicator radius
    this.targetRadius = 1;
}

// 更新函数firework
Firework.prototype.update = function( index ) {
    // 删除数组中的最后一个元素
    this.coordinates.pop();
    // 把当前坐标添加到最前面
    this.coordinates.unshift( [ this.x, this.y ] );

    // cycle the circle target indicator radius
    if( this.targetRadius < 8 ) {
        this.targetRadius += 0.3;
    } else {
        this.targetRadius = 1;
    }

    // 烟花函数的加速
    this.speed *= this.acceleration;

    // 获取基于角度跟速度的开始坐标
    var vx = Math.cos( this.angle ) * this.speed,
        vy = Math.sin( this.angle ) * this.speed;
    // 获取开始坐标跟加速度之后的坐标的距离
    this.distanceTraveled = calculateDistance( this.sx, this.sy, this.x + vx, this.y + vy );

    // if the distance traveled, including velocities, is greater than the initial distance to the target, then the target has been reached 创建颗粒
    if( this.distanceTraveled >= this.distanceToTarget ) {
        createParticles( this.tx, this.ty );
        // remove the firework, use the index passed into the update function to determine which to remove
        fireworks.splice( index, 1 );
    } else {
        // 还没到达目标坐标，继续运动
        this.x += vx;
        this.y += vy;
    }
}

// 绘画函数
Firework.prototype.draw = function() {
    ctx.beginPath();
    // 移动到当前位置的点画线
    ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
    ctx.lineTo( this.x, this.y );
    ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
    ctx.stroke();

    ctx.beginPath();
    // 在重点画半径随机的圆
    ctx.arc( this.tx, this.ty, this.targetRadius, 0, Math.PI * 2 );
    ctx.stroke();
}

// 创建颗粒效果
function Particle( x, y ) {
    this.x = x;
    this.y = y;
    // track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails
    this.coordinates = [];
    this.coordinateCount = 5;
    while( this.coordinateCount-- ) {
        this.coordinates.push( [ this.x, this.y ] );
    }
    // 设置0-360随机角度
    this.angle = random( 0, Math.PI * 2 );
    this.speed = random( 1, 10 );
    // 设置阻力
    this.friction = 0.95;
    // 设置重力数值
    this.gravity = 1;
    // 设置hsl颜色值的上下20波动的随机数和随机的s,l值
    this.hue = random( hue - 20, hue + 20 );
    this.brightness = random( 50, 80 );
    this.alpha = 1;
    // 设置随机的衰减值
    this.decay = random( 0.015, 0.03 );
}

// 更新粒子效果
Particle.prototype.update = function( index ) {
    // 移除最后一个元素
    this.coordinates.pop();
    // 把当前的坐标值添加进去
    this.coordinates.unshift( [ this.x, this.y ] );
    // 减速运动
    this.speed *= this.friction;
    // 设置加速后坐标
    this.x += Math.cos( this.angle ) * this.speed;
    this.y += Math.sin( this.angle ) * this.speed + this.gravity;
    // 设置alpha亮度随机数值
    this.alpha -= this.decay;

    // alpha值低于decay时，删除该坐标
    if( this.alpha <= this.decay ) {
        particles.splice( index, 1 );
    }
}

// 颗粒的绘画函数
Particle.prototype.draw = function() {
    ctx. beginPath();
    // 画直线
    ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
    ctx.lineTo( this.x, this.y );
    ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
    ctx.stroke();
}

// 创建颗粒爆炸数组
function createParticles( x, y ) {
    // increase the particle count for a bigger explosion, beware of the canvas performance hit with the increased particles though
    var particleCount = 30;
    while( particleCount-- ) {
        particles.push( new Particle( x, y ) );
    }
}

// 循环函数
function loop() {
    // this function will run endlessly with requestAnimationFrame
    requestAnimFrame( loop );

    // increase the hue to get different colored fireworks over time
    hue += 0.5;

    // normally, clearRect() would be used to clear the canvas
    // we want to create a trailing effect though
    // setting the composite operation to destination-out will allow us to clear the canvas at a specific opacity, rather than wiping it entirely
    ctx.globalCompositeOperation = 'destination-over';
    // decrease the alpha property to create more prominent trails
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
    ctx.fillRect( 0, 0, cw, ch );
    // change the composite operation back to our main mode
    // lighter creates bright highlight points as the fireworks and particles overlap each other
    ctx.globalCompositeOperation = 'lighter';

    // loop over each firework, draw it, update it
    var i = fireworks.length;
    while( i-- ) {
        fireworks[ i ].draw();
        fireworks[ i ].update( i );
    }

    // loop over each particle, draw it, update it
    var i = particles.length;
    while( i-- ) {
        particles[ i ].draw();
        particles[ i ].update( i );
    }

    // launch fireworks automatically to random coordinates, when the mouse isn't down
    if( timerTick >= timerTotal ) {
        if( !mousedown ) {
            // start the firework at the bottom middle of the screen, then set the random target coordinates, the random y coordinates will be set within the range of the top half of the screen
            fireworks.push( new Firework( cw / 2, ch, random( 0, cw ), random( 0, ch / 2 ) ) );
            timerTick = 0;
        }
    } else {
        timerTick++;
    }

    // limit the rate at which fireworks get launched when mouse is down
    if( limiterTick >= limiterTotal ) {
        if( mousedown ) {
            // start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target
            fireworks.push( new Firework( cw / 2, ch, mx, my ) );
            limiterTick = 0;
        }
    } else {
        limiterTick++;
    }
}

// mouse event bindings
// 鼠标移动时获取鼠标坐标
cav.addEventListener( 'mousemove', function( e ) {
    mx = e.clientX - cav.offsetLeft;
    my = e.clientY - cav.offsetTop;

});

// toggle mousedown state and prevent canvas from being selected
cav.addEventListener( 'mousedown', function( e ) {
    e.preventDefault();
    mousedown = true;
});

cav.addEventListener( 'mouseup', function( e ) {
    e.preventDefault();
    mousedown = false;
});
cav.addEventListener('touchstart', function(e){
    mousedown = true;
})
cav.addEventListener('touchmove',function(e){
    e.preventDefault();
    mx = e.touches[0].pageX;
    my = e.touches[0].pageY ;
})
cav.addEventListener('touchend' , function(e){
    mousedown = false;
})

// 页面加载后执行loop函数
window.onload = loop;
